package com.v1.video.option.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;

import com.v1.video.R;
  
/** 
 *  
 * 实现软件更新的管理类 
 */  
public class ApkDownLoadManager {  
	
	private Handler outHander = null; //用于回调发消息的handler
	private int outMsg;//用于回调发消息的内容  
	public static final String DOWNLOADDIR = Environment.getExternalStorageDirectory().getPath()
            + "/V1/Video/apk";
	//应用程序的包名 
	private String packageName = "";  
	private String fileName = "";
	private String fileUrl = "";
	
    //下载中...  
    private static final int DOWNLOAD = 1;  
    //下载完成  
    private static final int DOWNLOAD_FINISH = 2;  
    private static final int NEED_INSTALL = 3;
    private static final int GO_INSTALL = 4;
    private static final int DOWNLOAD_CANCEL = 2;

    //保存解析的XML信息  
    HashMap<String , String> mHashMap;  
    //下载保存路径  
    private String mSavePath;  
    //记录进度条进度
    private int progress;  
    //是否取消更新  
    private boolean cancelDownLoad = false;  
    //上下文对象  
    private Context mContext;  
    //进度条  
    private ProgressBar mProgressBar;  
    //更新进度条的对话框  
    private Dialog mDownloadDialog;  
      
    private Handler mHandler = new Handler() {  
        public void handleMessage(android.os.Message msg) {  
            if (msg.what == DOWNLOAD) {
				//更新进度条  
                System.out.println(progress);
				mProgressBar.setProgress(progress);
			} else if (msg.what == DOWNLOAD_FINISH) {
				// 安装文件  			    
                installApk();
			}  
			
        };  
    };
  
  
    public ApkDownLoadManager(Context context,String fileName,String fileUrl) {  
        super();  
        this.mContext = context;          
        this.fileName = fileName;
        this.fileUrl = fileUrl;
        mHashMap = new HashMap<String, String>();
    }        
      
    private void showNoticeDialog() {  
        // TODO Auto-generated method stub  
        //构造对话框  
        AlertDialog.Builder builder = new Builder(mContext);  
//        builder.setTitle(R.string.apk_download_title);  
        builder.setMessage(R.string.download_sure);  
        //下载
        builder.setPositiveButton(R.string.download_ok, new OnClickListener() {  
              
            @Override  
            public void onClick(DialogInterface dialog, int which) {  
                // TODO Auto-generated method stub  
                dialog.dismiss();  
                // 显示下载对话框  
                showDownloadDialog();  
            }  
        });  
        //取消下载  
        builder.setNegativeButton(R.string.download_cancel, new OnClickListener() {  
              
            @Override  
            public void onClick(DialogInterface dialog, int which) {  
                // TODO Auto-generated method stub  
                dialog.dismiss();  
                sendOutMsg(DOWNLOAD_CANCEL);
            }  
        });  
        Dialog noticeDialog = builder.create();  
        noticeDialog.show();  
    }  
      
    public void showDownloadDialog() {  
        // 构造软件下载对话框  
        AlertDialog.Builder builder = new Builder(mContext);  
        builder.setTitle(R.string.apk_downloading_title);  
        // 给下载对话框增加进度条  
        final LayoutInflater inflater = LayoutInflater.from(mContext);  
        View view = inflater.inflate(R.layout.dialog_download_progress, null);  
        mProgressBar = (ProgressBar) view.findViewById(R.id.download_progress);  
        builder.setView(view);  
        builder.setNegativeButton(R.string.apk_downloading_cancel, new OnClickListener() {  
              
            @Override  
            public void onClick(DialogInterface dialog, int which) {  
                // TODO Auto-generated method stub  
                dialog.dismiss();  
                // 设置取消状态  
                cancelDownLoad = true;  
                sendOutMsg(DOWNLOAD_CANCEL);
            }  
        });  
        mDownloadDialog = builder.create();  
        mDownloadDialog.show();  
        //下载文件  
        downloadApk();  
    }  
      
    /** 
     * 下载APK文件 
     */  
    private void downloadApk() {  
        // TODO Auto-generated method stub  
        // 启动新线程下载软件  
        new DownloadApkThread().start();  
    }  
  
    /** 
     * 下载文件线程 
     * @author Administrator 
     * 
     */  
    private class DownloadApkThread extends Thread {  
        @Override  
        public void run() {  
            try  
            {  
                //判断SD卡是否存在，并且是否具有读写权限  
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))  
                {  
                    // 获取SDCard的路径  
//                    String sdpath = DOWNLOADDIR + "/"+fileName;  
//                    mSavePath = sdpath + "download";  
                    URL url = new URL(fileUrl);  
                    // 创建连接  
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
                    conn.connect();  
                    // 获取文件大小  
                    int length = conn.getContentLength();  
                    // 创建输入流  
                    InputStream is = conn.getInputStream();  
  
                    File file = new File(DOWNLOADDIR);  
                    // 如果文件不存在，新建目录  
                    if (!file.exists())  
                    {  
                        file.mkdirs();
//                        file.createNewFile();
                    }  
                    long curSize = 0;
//                    File apkFile = new File(DOWNLOADDIR, fileName+".apk");
                    File apkFile = new File(DOWNLOADDIR+"/"+fileName+".apk");  
                    if(!apkFile.exists()){
                        apkFile.createNewFile();
                    }else{
                        curSize = file.length();
                    }
                    if(length > 0 && curSize >= length){
                        progress = 100;
                        mHandler.sendEmptyMessage(DOWNLOAD_FINISH);  
                        return;
                    }
                    
                    FileOutputStream fos = new FileOutputStream(apkFile);
//                    FileOutputStream fos = new FileOutputStream(file);  
                    int count = 0;  
                    // 缓存  
                    byte buf[] = new byte[1024];  
                    // 写入到文件中  
                    do  
                    {  
                        int numread = is.read(buf);  
                        count += numread;  
                        // 计算进度条的位置  
                        progress = (int) (((float) count / length) * 100);  
                        // 更新进度  
                        mHandler.sendEmptyMessage(DOWNLOAD);  
                        if (numread <= 0)  
                        {  
                            // 下载完成  
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);  
                            break;  
                        }  
                        // 写入文件  
                        fos.write(buf, 0, numread);  
                    } while (!cancelDownLoad);//点击取消就停止下载  
                    fos.close();  
                    is.close();  
                }  
            } catch (MalformedURLException e)  
            {  
                e.printStackTrace();  
            } catch (IOException e)  
            {  
                e.printStackTrace();  
            }  
            // 取消下载对话框显示  
            mDownloadDialog.dismiss();  
        }  
    }  
      
    /** 
     * 安装APK文件 
     */  
    private void installApk()  
    {  
        File apkfile = new File(DOWNLOADDIR, fileName+".apk");  
        if (!apkfile.exists())  
        {  
            return;  
        }  
        Intent i = new Intent(Intent.ACTION_VIEW);  
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");  
        mContext.startActivity(i);  
        sendOutMsg(GO_INSTALL);
    }   
	
	private void sendOutMsg(int outMsg){
		if(outHander!=null){
		// 给主线程发消息
			Message msg = new Message();
			msg.what = outMsg;
			outHander.sendMessage(msg);
		}
	}
}  